﻿namespace Vdc.Interface
{
    using Vdc.Interface.Design;
    using Vdc.Interface.Interfaces;
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.ComponentModel.Design;
    using System.Text;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.HtmlControls;

    [ParseChildren(true), PersistChildren(false), Designer(typeof(VdcTextBoxDesigner), typeof(IDesigner))]
    public class VdcButton : Button, IVdcControl, IButtonControl
    {
        private static Hashtable availableClientIds = new Hashtable();
        private string clientObjectID;
        private VdcButtonClientSideEvents clientSideEvents = new VdcButtonClientSideEvents();
        private VdcButtonCssSettings cssSettings = new VdcButtonCssSettings();
        private List<HtmlLink> htmlLinksAddedToHead;
        private bool IsFocused;
        private VdcDiv mainContainer;
        internal ScriptManagerHelper MyScriptManager;
        private Literal scriptContainerContent;

        protected override void CreateChildControls()
        {
            this.mainContainer = new VdcDiv();
            this.mainContainer.CssClass = this.Enabled ? this.CssSettings.Container_Normal : this.CssSettings.Container_Disabled;
            this.mainContainer.Width = this.Width;
            this.mainContainer.ID = this.GetContainerID();
            this.mainContainer.ToolTip = this.ToolTip;
            VdcDiv div = VdcControlFactory.CreateSection(this, "ob_iBL");
            VdcDiv div2 = VdcControlFactory.CreateSection(this, "ob_iBR");
            VdcDiv div3 = VdcControlFactory.CreateSection(this, "ob_iBC");
            VdcDiv child = new VdcDiv();
            Literal literal = new Literal {
                Text = base.Text
            };
            Button targetControl = VdcCloner.CloneButton(this);
            targetControl.ID = this.UniqueID;
            ClientScriptManager clientScript = this.Page.ClientScript;
            PostBackOptions options = new PostBackOptions(targetControl) {
                ActionUrl = this.PostBackUrl,
                ValidationGroup = this.ValidationGroup,
                PerformValidation = this.CausesValidation,
                ClientSubmit = !this.UseSubmitBehavior,
                TrackFocus = false
            };
            targetControl.Attributes["onclick"] = clientScript.GetPostBackEventReference(options);
            child.Controls.Add(literal);
            div3.Controls.Add(child);
            div3.Controls.Add(targetControl);
            VdcControlFactory.CreateSection(this, "ob_iBOv");
            VdcControlFactory.CreateChildControls(this);
            if (VdcControlFactory.IsDesignTimeRender(this))
            {
                this.mainContainer.Style["float"] = "left";
                if (string.IsNullOrEmpty(this.FolderStyle))
                {
                    div.Style["background-image"] = VdcControlFactory.GetEmbeddedImageUrl(this, "button.png");
                    div2.Style["background-image"] = VdcControlFactory.GetEmbeddedImageUrl(this, "button.png");
                    div3.Style["background-image"] = VdcControlFactory.GetEmbeddedImageUrl(this, "button.png");
                }
            }
            base.CreateChildControls();
        }

        public override void Focus()
        {
            this.IsFocused = true;
            base.Focus();
        }

        protected virtual string GetButtonID()
        {
            return this.UniqueID;
        }

        protected virtual string GetContainerID()
        {
            return ("ob_iB" + this.ClientObjectID + "Container");
        }

        public static string GetLinkToEmbeddedStyleSheet()
        {
            return "Vdc.Interface.VdcButton.resources.styles.black_glass.style.css";
        }

        string IVdcControl.CreateClientScript(bool createOnlyClientObject)
        {
            StringBuilder builder = new StringBuilder();
            builder.Append(" if(typeof(" + this.ClientObjectID + ")!='undefined'){if(typeof(" + this.ClientObjectID + ".destruct)=='function'){" + this.ClientObjectID + ".destruct();}}");
            if (!createOnlyClientObject)
            {
                builder.Append("var " + this.ClientObjectID + ";");
                builder.Append("function initButton__" + this.ClientObjectID + "(attempts){ ");
                builder.Append("if(typeof(vdcButtonJSLoaded) == \"undefined\" || typeof(Vdc.Interface.VdcButton) == \"undefined\") {if(attempts<30){window.setTimeout(\"initButton__" + this.ClientObjectID + "(\" + (attempts+1) + \")\", 500);}else{alert(\"There was a problem referencing Button javascript files.  Please contact vdccontrol@gmail.com for support.\");}return;}");
                builder.Append("try{");
            }
            builder.Append(this.ClientObjectID + " = new Vdc.Interface.VdcButton(");
            builder.Append("\"" + this.ClientObjectID + "\",");
            builder.Append("\"" + this.mainContainer.ClientID + "\",");
            builder.Append("\"" + this.Width.ToString() + "\",");
            builder.Append(this.Enabled.ToString().ToLower() + ",");
            builder.Append(this.IsFocused.ToString().ToLower() + ",");
            builder.Append(this.CssSettings.SerializeToJSON() + ",");
            builder.Append(createOnlyClientObject.ToString().ToLower());
            builder.Append(");");
            if (!createOnlyClientObject)
            {
                builder.Append("}catch(e){alert(\"There was an error initializing Button with ID " + this.ClientObjectID + ".\\n\\n\" + e.message + \"\\n\\nPlease contact vdccontrol@gmail.com for help.\");}}");
                builder.Append(" initButton__" + this.ClientObjectID + "(0); ");
            }
            return builder.ToString();
        }

        void IVdcControl.ForceCreateChildControls()
        {
            this.CreateChildControls();
        }

        protected override void OnInit(EventArgs e)
        {
            VdcControlFactory.Init(this);
            base.OnInit(e);
        }

        protected override void OnPreRender(EventArgs e)
        {
            VdcControlFactory.RegisterClientScripts(this, null, null);
            base.OnPreRender(e);
        }

        public static void RegisterClientScripts(Control control)
        {
            ScriptManagerHelper scriptManager = new ScriptManagerHelper(control);
            VdcControlFactory.RegisterClientScripts(control, typeof(VdcButton), scriptManager);
        }

        protected override void Render(HtmlTextWriter writer)
        {
            this.EnsureChildControls();
            VdcControlFactory.Render(this, writer);
        }

        protected string ClientObjectID
        {
            get
            {
                if (string.IsNullOrEmpty(this.clientObjectID))
                {
                    this.clientObjectID = VdcControlFactory.GetClientObjectID(this);
                }
                return this.clientObjectID;
            }
            set
            {
                this.clientObjectID = value;
            }
        }

        [Description("Property used to define the Client-Side Events."), Bindable(true), PersistenceMode(PersistenceMode.InnerProperty), DesignerSerializationVisibility(DesignerSerializationVisibility.Visible), NotifyParentProperty(true), Category("Client-Side Events")]
        public VdcButtonClientSideEvents ClientSideEvents
        {
            get
            {
                return this.clientSideEvents;
            }
            set
            {
                this.clientSideEvents = value;
            }
        }

        [PersistenceMode(PersistenceMode.InnerProperty), NotifyParentProperty(true), Bindable(true), DesignerSerializationVisibility(DesignerSerializationVisibility.Visible), Category("CSS Settings"), Description("Property used to define the CSS Settings.")]
        public VdcButtonCssSettings CssSettings
        {
            get
            {
                return this.cssSettings;
            }
            set
            {
                this.cssSettings = value;
            }
        }

        [Bindable(true), Description("The folder containing the css stylesheet.")]
        public string FolderStyle
        {
            get
            {
                object obj2 = this.ViewState["FolderStyle"];
                if (obj2 != null)
                {
                    return obj2.ToString();
                }
                return string.Empty;
            }
            set
            {
                this.ViewState["FolderStyle"] = value;
            }
        }

        Hashtable IVdcControl.AvailableClientIds
        {
            get
            {
                return availableClientIds;
            }
        }

        VdcDiv IVdcControl.Container
        {
            get
            {
                return this.mainContainer;
            }
        }

        bool IVdcControl.HasChildControlsCreated
        {
            get
            {
                return base.ChildControlsCreated;
            }
        }

        List<HtmlLink> IVdcControl.HtmlLinksAddedToHead
        {
            get
            {
                if (this.htmlLinksAddedToHead == null)
                {
                    this.htmlLinksAddedToHead = new List<HtmlLink>();
                }
                return this.htmlLinksAddedToHead;
            }
        }

        bool IVdcControl.IsDesignTimeRender
        {
            get
            {
                return base.DesignMode;
            }
        }

        string IVdcControl.LinkToEmbeddedStyleSheet
        {
            get
            {
                return GetLinkToEmbeddedStyleSheet();
            }
        }

        Literal IVdcControl.ScriptContainerContent
        {
            get
            {
                return this.scriptContainerContent;
            }
            set
            {
                this.scriptContainerContent = value;
            }
        }

        ScriptManagerHelper IVdcControl.ScriptManager
        {
            get
            {
                return this.MyScriptManager;
            }
            set
            {
                this.MyScriptManager = value;
            }
        }

        bool IVdcControl.StyleSheetReferenceAdded
        {
            get
            {
                return HttpContext.Current.Items.Contains("vdcButton_StyleSheetAdded");
            }
            set
            {
                if (value)
                {
                    HttpContext.Current.Items.Add("vdcButton_StyleSheetAdded", true);
                }
                else
                {
                    HttpContext.Current.Items.Remove("vdcButton_StyleSheetAdded");
                }
            }
        }
    }
}

